﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Security.Cryptography;
using System.Collections.Specialized;
using System.IO;
using System.Data.SqlClient;
using System.Net;

using Shove.Alipay;

public partial class OnlinePay_Alipay02_AlipayNotify : PageBase
{
    SystemOptions s = new SystemOptions();//读取系统设置tbl_Options里的总站支付配置信息,若要设置店铺的支付设置,请查询tbl_Shop表

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            //***************************************************************     
            string _input_charset = "utf-8";
            string NotifyService = "notify_verify";
            string SellerEmail = s["Opt_OnlinePay_Alipay_UserName"].ToString("");//卖家支付宝名称(邮箱)

            string NotifyID = Request.Form["notify_id"];

            int NotifyType = 2;

            Alipay ap = new Alipay();

            //获取支付宝ATN返回结果，true是正确的订单信息，false 是无效的
            string responseTxt = ap.Get_Http(NotifyService, NotifyID, SellerEmail, _input_charset, NotifyType, 120000);

            int i;
            NameValueCollection coll;
            //Load Form variables into NameValueCollection variable.
            coll = Request.Form;

            // Get names of all forms into a string array.
            String[] requestarr = coll.AllKeys;

            //进行排序；
            string[] Sortedstr = Alipay.BubbleSort(requestarr);

            //构造待md5摘要字符串 ；

            StringBuilder prestr = new StringBuilder();

            for (i = 0; i < Sortedstr.Length; i++)
            {
                if (Request.Form[Sortedstr[i]] != "" && Sortedstr[i] != "sign" && Sortedstr[i] != "sign_type")
                {
                    if (i == Sortedstr.Length - 1)
                    {
                        prestr.Append(Sortedstr[i] + "=" + Request.Form[Sortedstr[i]]);
                    }
                    else
                    {
                        prestr.Append(Sortedstr[i] + "=" + Request.Form[Sortedstr[i]] + "&");

                    }
                }
            }

            string mysign = ap.GetMD5(prestr.ToString(), SellerEmail, _input_charset);

            string sign = Request.Form["sign"];
            string trade_status = Request.Form["trade_status"];
            string trade_no = Request.Form["trade_no"];              //支付宝交易号
            string out_trade_no = Request.Form["out_trade_no"];      //自己交易号
            //string payment_type = Request.Form["payment_type"];      //支付类型
            string subject = Request.Form["subject"];                //商品名称，用户存放用户ID
            string subject_UnEncrypt = Shove._Security.Encrypt.UnEncryptString(PublicFunction.GetCallCert(), subject);
            double total_fee = Shove._Convert.StrToDouble(Request.Form["total_fee"].ToString(), 0);  //支付金额
            string seller_email = Request.Form["seller_email"];      //卖家账号

            if (seller_email != SellerEmail)
            {
                //PublicFunction.WriteLog(_Site, "支付用户信息验证失败！(Notify)");

                Response.Write("fail");     //返回给支付宝消息，失败

                Response.End();

                return;
            }

            if (mysign == sign && responseTxt == "true" && trade_status == "TRADE_FINISHED")   //验证支付发过来的消息，签名是否正确
            {
                Customer customer;

                if (_Customer == null)
                {
                    customer = new Customer(_Site.ID)[_Site.ID, Shove._Convert.StrToLong(subject_UnEncrypt, -1)];
                }
                else
                {
                    customer = new Customer(_Site.ID)[_Site.ID, _Customer.ID];
                }

                if (customer == null)
                {
                    PublicFunction.GoError(ErrorNumber.Unknow, "异常用户数据", this.GetType().BaseType.FullName);

                    return;
                }

                if (_Customer == null)
                {
                    _Customer = new Customer(_Site.ID)[_Site.ID, customer.ID];

                    string ReturnDescription = "";
                    _Customer.LoginDirect(ref ReturnDescription);
                }

                if (WriteUserAccount(_Customer, out_trade_no.ToString(), total_fee.ToString(), "系统交易号：" + out_trade_no.ToString() + ",支付宝交易号：" + trade_no.ToString()))
                {
                    Response.Write("success");     //返回给支付宝消息，成功
                    Response.End();

                    return;
                }
                else
                {
                    //PublicFunction.WriteLog(_Site, "写入返回数据出错！(Notify)");
                    Response.Write("fail");
                    Response.End();

                    return;
                }
            }
            else
            {
                //PublicFunction.WriteLog(_Site, "(Notify)系统交易号：" + out_trade_no + " 支付宝交易号：" + trade_no + " 校验出错！responseTxt系统要求参数为true/false，实际返回：" + responseTxt.ToString() + " trade_status系统要求返回TRADE_FINISHED，实际返回： " + trade_status.ToString() + " 生成校验码：" + mysign.ToString() + "返回校验码：" + sign.ToString());
                Response.Write("fail");
                Response.End();

                return;
            }
        }
        catch
        {
            //PublicFunction.WriteLog(_Site, Ex.Message);
            Response.Write("fail");
            Response.End();

            return;
        }
    }

    private bool WriteUserAccount(Customer _Customer, string orderid, string amount, string Memo)
    {
        double Money = Shove._Convert.StrToDouble(amount, 0);
        if (Money == 0)
        {
            return false;
        }

        double FormalitiesFeesScale = s["Opt_OnlinePay_Alipay_PayFormalitiesFeesScale"].ToDouble(0) / 100;
        double FormalitiesFees = Money - Math.Round(Money / (FormalitiesFeesScale + 1), 2);
        Money -= FormalitiesFees;

        string ReturnDescription = "";
        bool ok = (_Customer.AddUserBalance(1, Money, FormalitiesFees, orderid, "支付宝支付", Memo, ref ReturnDescription) == 0);

        if (!ok)
        {
            DataTable dt = new DAL.Tables.tbl_CustomerPayDetails().Open("Result", "[id] = " + Shove._Convert.StrToLong(orderid, 0).ToString(), "");

            if (dt == null || dt.Rows.Count == 0)
            {
                //返回的交易号找不到对应的数据
                return false;
            }

            int IsOK = Shove._Convert.StrToInt(dt.Rows[0][0].ToString(), 0);

            if (IsOK == 1)
            {
                return true;
            }
            else
            {
                //对应的数据未处理
                return false;
            }
        }

        return ok;
    }
}